/* $Id : selectzone.js 4824 2007-01-31 08:23:56Z paulgao $ */

/* *
 * SelectZone 类
 */
function SelectZone()
{
    this.filters   = new Object();

    this.id        = arguments[0] ? arguments[0] : 1;     // 过滤条件
    this.sourceSel = arguments[1] ? arguments[1] : null;  // 1 商品关联 2 组合、赠品（带价格）
    this.targetSel = arguments[2] ? arguments[2] : null;  // 源   select 对象
    this.priceObj  = arguments[3] ? arguments[3] : null;  // 目标 select 对象
	var $sourceSel=$('select[name="'+this.sourceSel.name+'"]');
	var $targetSel=$('select[name="'+this.targetSel.name+'"]');
	var $sourceNumber=$('#'+$sourceSel.attr('name')+'_number');
	var $sourcePrice=$('#'+$sourceSel.attr('name')+'_price');
	var $targetNumber=$('#'+$targetSel.attr('name')+'_number');
	var $targetPrice=$('#'+$targetSel.attr('name')+'_price');
	var $targetHidden=$('#'+$targetSel.attr('name')+'_hidden');
	//console.log($sourcePrice);
    this.filename  = location.href.substring((location.href.lastIndexOf("/")) + 1, location.href.lastIndexOf("?")) + "?is_ajax=1";
    var _self = this;

    /**
   * 载入源select对象的options
   * @param   string      funcName    ajax函数名称
   * @param   function    response    处理函数
   */
    this.loadOptions = function(act, filters)
    {
        Ajax.call(this.filename+"&act=" + act, filters, this.loadOptionsResponse, "GET", "JSON");
    }

    /**
   * 将返回的数据解析为options的形式
   * @param   result      返回的数据
   */
    this.loadOptionsResponse = function(result, txt)
    {
        if (!result.error)
        {
			_self.sourceSel.length=0;
            _self.createOptions(_self.sourceSel, result.content);
        }

        if (result.message.length > 0)
        {
            alert(result.message);
        }
        return;
    }

    /**
   * 检查对象
   * @return boolean
   */
    this.check = function()
    {
        /* source select */
        if ( ! this.sourceSel)
        {
            alert('source select undefined');
            return false;
        }
        else
        {
            if (this.sourceSel.nodeName != 'SELECT')
            {
                alert('source select is not SELECT');
                return false;
            }
        }

        /* target select */
        if ( ! this.targetSel)
        {
            alert('target select undefined');
            return false;
        }
        else
        {
            if (this.targetSel.nodeName != 'SELECT')
            {
                alert('target select is not SELECT');
                return false;
            }
        }

        return true;
    }

    /**
   * 添加选中项
   * @param   boolean  all
   */
    this.addItem = function(all)
    {
		if (!this.check())
		{
			return;
		}
		var selOpt  = new Array();

		for (var i = 0; i < this.sourceSel.length; i ++ )
		{
			function add(){
				var arr=new Array();
				var item={
					goods_id:$('option',$sourceSel).eq(i).attr('goods_id'),
					goods_name:$('option',$sourceSel).eq(i).attr('goods_name'),
					goods_number:typeof($sourceNumber.val())=="undefined"?$('option',$sourceSel).eq(i).attr('goods_number'):$sourceNumber.val(),
					goods_price:typeof($sourcePrice.val())=="undefined"?$('option',$sourceSel).eq(i).attr('goods_price'):$sourcePrice.val()
				};
				arr.push(item);
				_self.createOptions(_self.targetSel, arr);					
			}
			if (!this.sourceSel.options[i].selected && all == false) continue;

			if (this.targetSel.length > 0)
			{
				var exsits = false;
				for (var j = 0; j < this.targetSel.length; j ++ )
				{
					if ($('option',$(this.targetSel)).eq(j).attr('goods_id')==
						$('option',$(this.sourceSel)).eq(i).attr('goods_id')){
						exsits = true;
						break;
					}	
				}
				if (!exsits){
					add();
				}
			}
			else{
				add();
			}
		}
		_self.assign_hidden();
    }
	this.update=function(act,id){ 
		$.post(this.filename+ "&act="+act,{ 
			id:id,
			list:$targetHidden.val()
		},function(data){ 
			
		},'json');
	}
    /**
   * 删除选中项
   * @param   boolean    all
   */
    this.dropItem = function(all)
    {
        if (!this.check())
        {
            return;
        }
		
        var arr = new Array();

        for (var i = this.targetSel.length - 1; i >= 0 ; i -- )
        {
            if (this.targetSel.options[i].selected || all){
				$('option',$(this.targetSel)).eq(i).remove();
            }
        }
		_self.assign_hidden();
    }

    /**
   * 处理添加项返回的函数
   */
    this.addRemoveItemResponse = function(result,txt)
    {
        if (!result.error)
        {
            _self.createOptions(_self.targetSel, result.content);
        }

        if (result.message.length > 0)
        {
            alert(result.message);
        }
    }

    /**
   * 为select元素创建options
   */
    this.createOptions = function(obj, arr)
    {
        for (var i=0; i < arr.length; i++)
        {
			var content="<option value='"+arr[i].goods_id+"' \
			goods_id='"+arr[i].goods_id+"' \
			goods_number='"+arr[i].goods_number+"' \
			goods_price='"+arr[i].goods_price+"' \
			goods_name='"+arr[i].goods_name+"'>"
				+arr[i].goods_name+"["+arr[i].goods_number+","+arr[i].goods_price+"]</option>";
			$(obj).append(content);
        }
		_self.assign_hidden();
    }
	this.editItem=function(obj){ 
		$option=$("option:selected",$(obj));
		try{ 
			$('#'+$(obj).attr('name')+'_number')
				.val($option.attr('goods_number'))
				.blur(function(){ 
					$option.attr('goods_number',$(this).val());
					$option.html($option.attr('goods_name')
						+"["+parseInt($option.attr('goods_number'))+","+parseFloat($option.attr('goods_price'))+"]");
					_self.assign_hidden();
				});
			$('#'+$(obj).attr('name')+'_price')
				.val($option.attr('goods_price'))
				.blur(function(){ 
					$option.attr('goods_price',$(this).val());
					$option.html($option.attr('goods_name')
						+"["+parseInt($option.attr('goods_number'))+","+parseFloat($option.attr('goods_price'))+"]");
					_self.assign_hidden();
				});		
		}catch(e){}
	} 	
	this.assign_hidden=function(){ 
		var res=new Array();
		
		$("option",$targetSel).each(function(){ 
			var item=new Object();
			item.goods_id=$(this).attr('goods_id');
			item.goods_name=$(this).attr('goods_name');
			item.goods_number=$(this).attr('goods_number');
			item.goods_price=$(this).attr('goods_price');
			res.push(item);
		});
		$('#'+$targetSel.attr('name')+'_hidden').val(res.toJSONString());
	}
	$(function(){ 
		_self.assign_hidden();
	});
}
